import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:go_pet/src/features/login/services/snack_bar.dart';
import 'package:go_pet/src/features/login/view/widgets/components/my_button.dart';
import 'package:go_pet/src/features/login/view/widgets/components/my_textfield.dart';
import 'package:go_pet/src/theme/app_colors.dart';
import 'package:go_pet/src/theme/image_sources.dart';

class LoginScreen extends StatefulWidget {
  const LoginScreen({super.key});

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  bool isHiddenPassword = true;
  TextEditingController emailTextInputController = TextEditingController();
  TextEditingController passwordTextInputController = TextEditingController();
  final formKey = GlobalKey<FormState>();

  @override
  void dispose() {
    emailTextInputController.dispose();
    passwordTextInputController.dispose();

    super.dispose();
  }

  void togglePasswordView() {
    setState(() {
      isHiddenPassword = !isHiddenPassword;
    });
  }

  Future<void> login() async {
    final navigator = Navigator.of(context);

    final isValid = formKey.currentState!.validate();
    if (!isValid) return;

    try {
      await FirebaseAuth.instance.signInWithEmailAndPassword(
        email: emailTextInputController.text.trim(),
        password: passwordTextInputController.text.trim(),
      );
    } on FirebaseAuthException catch (e) {
      if (e.code == 'user-not-found' || e.code == 'wrong-password') {
        SnackBarService.showSnackBar(
          context,
          'Неправильный email или пароль. Повторите попытку',
          true,
        );
        return;
      } else {
        SnackBarService.showSnackBar(
          context,
          'Неизвестная ошибка! Попробуйте еще раз или обратитесь в поддержку.',
          true,
        );
        return;
      }
    }

    navigator.pushNamedAndRemoveUntil('/home', (Route<dynamic> route) => false);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: const Text('Вход'),
      ),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 25),
        child: Form(
          key: formKey,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                children: [
                  const SizedBox(
                    height: 100,
                  ),

                  //TODO: gopet logo
                  const Icon(
                    Icons.people,
                    size: 80,
                    color: AppColors.primary,
                  ),

                  const SizedBox(height: 25),

                  // app name
                  Image.asset(
                    ImageSources.appname,
                    height: 30,
                  ),

                  const SizedBox(height: 50),

                  MyTextField(
                    obscureText: false,
                    controller: emailTextInputController,
                    hintText: 'Email',
                  ),
                  const SizedBox(height: 15),
                  MyTextField(
                    controller: passwordTextInputController,
                    obscureText: isHiddenPassword,
                    hintText: 'Пароль',
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      TextButton(
                        onPressed: () =>
                            Navigator.of(context).pushNamed('/reset_password'),
                        child: const Text(
                          'Сбросить пароль?',
                          style: TextStyle(color: AppColors.black),
                        ),
                      ),
                    ],
                  )
                ],
              ),
              Column(
                children: [
                  MyButton(
                    onTap: login,
                    text: 'Войти',
                  ),
                  const SizedBox(height: 15),
                  const Text(
                    "ИЛИ",
                    style: TextStyle(
                      color: AppColors.black,
                    ),
                  ),
                  TextButton(
                    onPressed: () => Navigator.of(context).pushNamed('/signup'),
                    child: Text(
                      'Регистрация',
                      style: Theme.of(context).textTheme.titleMedium,
                    ),
                  ),
                  const SizedBox(height: 30),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
